/**
 * 名称：设计器核心Js
 * 作者：袁泉
 * 创建时间：2018年6月3日12:48:25
 * 版本：v1.0
 * 更新时间：2018年6月16日11:44:48
 */
var drag = {
    cont: {
        mainPanleMaxHeight: 0, mainPanleMaxWidth: 0,//面板的最大宽高（当前宽高）
        mWarpTop: 0, mWarpLeft: 0,//面板的最高坐标和最左坐标
        mainPanleMinWidth: 400, mainPanleMinHeight: 500,//面板的最小宽高
        widgetMinWidth: 100, widgetMinHeight: 25,//控件的最小宽高

        widget: {
            "type": "textbox",
            "x": 237,
            "y": 13,
            "cls": "widgetItem",
            "name": '',
            "id": 'widget',
            "width": 200,
            "height": 20,
            "labelWidth": 70,
            "fieldLabel": "未命名",
            "value": ""
        },
        isCtrl: false,
        isShift: false
    },
    util: {
        replacePx: function (val) {
            return parseInt(val.replace('px', ''));
        },
        replaceDrag: function (val) {
            return val.replace('Drag', '');
        },
        uuid: function (len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;

            if (len) {
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        }
    },
    options: {
        elm: '',
        //回调事件
        event: {
            //主面板点击事件
            panelClickCallback: function () {
            },
            //初始化完成回调事件
            initCallback: function () {
            },
            /**
             * 开始移动回调事件
             * @param current 当前控件
             * @param e 事件
             */
            startMoveCallback: function (current, e) {
            },
            /***
             * 移动中回调事件
             * @param a 拖动参数
             * @param b 拖动参数
             * @param c 拖动参数
             */
            moveCallback: function (a, b, c) {
            },
            /***
             * 结束移动回调事件
             * @param a 拖动参数a
             * @param b 拖动参数b
             * @param l left
             * @param t top
             **/
            stopMoveCallback: function (a, b, l, t) {
            },
            //大小被改变事件
            resize: function () {
            },
            /***
             * 停止改变大小事件
             * @param target 目前拖拽控件的dom
             * @param w 宽度
             * @param h 高度
             */
            stopResize: function (target, w, h) {
            },
            //开始拖动大小回调事件
            startResize: function () {
            },
            /***
             * 控件被单击回调事件
             * @param thats
             * @param that
             * @param isMulti
             */
            widgetClick: function (thats, that, isMulti) {
            },
            /***
             * 主面板尺寸被改变
             * @param width  宽度
             * @param height 高度
             */
            mianPanelSizeChange: function (width, height) {
            }


        },
        isDefEv: true,//是否具备默认事件
    },
    /***
     * @param callBack 回调事件
     */
    init: function (param) {
        drag.options = $.extend(true, drag.options, param);
        /**************初始化画布************************/
        //初始化第一个form的宽高拖动
        drag.initMainPanle();
        //初始化所有控件
        $(drag.options.elm).each(function () {
            var that = $(this);
            //如果该控件没有被渲染过（上级节点没有weight Class），就渲染该控件
            if (!$(that.parent()[0]).hasClass('weight')) {
                drag.renderWidget(that);
            }

        });
    },
    /***
     * 初始化主面板的拖拽事件
     */
    initMainPanle: function () {
        var mainPanle = $($('.canvas').find('form')[0]);
        var mainPanleDSize = mainPanle.ligerResizable({handles: 'e,s'});
        drag.cont.maxWidth = mainPanle.width();
        drag.cont.maxHeight = mainPanle.height();

        drag.cont.mWarpLeft = mainPanle.offset().left;
        drag.cont.mWarpTop = mainPanle.offset().top;

        mainPanleDSize.bind('StopResize', function (e) {
            var that = $(this.target);
            var type = e.dir;
            //拖动右边的时候
            if (type == 'e') {
                if (e.newWidth < drag.cont.mainPanleMinWidth) {
                    that.css('width', drag.cont.mainPanleMinWidth + 'px')
                    drag.cont.mainPanleMaxWidth = drag.cont.mainPanleMinWidth;
                } else {
                    drag.cont.mainPanleMaxWidth = e.newWidth;
                }
            }
            //拖动底边的时候
            if (type == 's') {
                if (e.newHeight < drag.cont.mainPanleMinHeight) {
                    that.css('height', drag.cont.mainPanleMinHeight + 'px')
                    drag.cont.mainPanleMaxHeight = drag.cont.mainPanleMinHeight;
                } else {
                    drag.cont.mainPanleMaxHeight = e.newHeight;
                }
            }
            drag.options.event.mianPanelSizeChange(drag.cont.mainPanleMaxWidth, drag.cont.mainPanleMaxHeight);
        });
        $('.canvas').unbind('click').on('click', function () {
            drag.options.event.panelClickCallback();
        });
    },
    /**
     * 渲染一个控件
     * @param that
     */
    renderWidget: function (that) {
        var isNoDrag = that.hasClass('noDrag');
        var isNoSize = that.hasClass('noSize');
        console.log(isNoSize, isNoDrag)
        if (isNoDrag && isNoSize) {
            that.addClass('weight');
            that.attr('id', that.data('id') + 'Drag');
        } else {
            var sDiv = $('<div></div>');
            that.addClass('abs');
            var widgetWidth = that.width() + 0.8;
            var widgetHeight = that.height();
            var wrap = sDiv.clone(true);
            wrap.width(widgetWidth);
            wrap.height(widgetHeight);
            wrap.addClass('weight');
            wrap.attr('id', that.attr('id') + 'Drag');
            //把控件的top/left属性放到拖拽容器上
            wrap.css({'z-index': that.css('z-index')});
            wrap.css({'top': that.css('top')});
            wrap.css({'left': that.css('left')});
            that.css('top', '0px');
            that.css('left', '0px');
            that.wrap(wrap);

            var widgetItem = that.parent();
            if (!isNoDrag) {
                if (!drag.options.isDefEv) {
                    //创建一个一样大小的透明DIV，挡住控件上方，防止触发控件默认输入事件
                    var gDiv = sDiv.clone(true);
                    gDiv.width(widgetWidth);
                    gDiv.height(widgetHeight);
                    gDiv.addClass('abs');
                    gDiv.css({'z-index': that.css('z-index') + 1});
                    that.after(gDiv[0]);
                }
                //拖拽
                var widgetDrag = widgetItem.ligerDrag({dragWarp: that.parents('.u-panle')[0], proxy: false});
                //绑定开始拖动事件
                widgetDrag.unbind('StartDrag');
                widgetDrag.bind('StartDrag', function (current, e) {
                    //开始拖动回调
                    drag.options.event.startMoveCallback(current, e);
                });
                //绑定拖动后事件
                widgetDrag.unbind('StopDrag');
                widgetDrag.bind('StopDrag', function (a, b) {
                    //停止拖动回调
                    var l = drag.util.replacePx(a.target.css('left'));// - mWarp.offset().left;
                    var t = drag.util.replacePx(a.target.css('top'));// - mWarp.offset().top;
                    drag.options.event.stopMoveCallback(a, b, l, t);
                });

            }
            if (!isNoSize) {
                //拖拽
                var dragSizeB = sDiv.clone(true);
                dragSizeB.html('　');
                dragSizeB.css({
                    width: '100%',
                    height: '5px',
                    // background:'#ff00ff',
                    position: 'absolute',
                    top: that.height() - 5,
                    zIndex: that.css('zIndex') + 1,
                    cursor: 's-resize'
                })
                var dragSizeR = sDiv.clone(true);
                dragSizeR.html('　');
                dragSizeR.css({
                    width: '5px',
                    height: '100%',
                    // background:'#ea0054',
                    position: 'absolute',
                    left: that.width() - 5,
                    zIndex: that.css('zIndex') + 1,
                    cursor: 'e-resize'
                })
                that.after(dragSizeB);
                that.after(dragSizeR);

                //拖size
                var widgetSize = widgetItem.ligerResizable({handles: 'e, se, ne,s'});
                widgetDrag.bind('Drag', function (a, b, c) {
                    var widget = $(a.target).parent().find('.widgetItem');
                });
                widgetSize.bind('StopResize', function (e) {
                    drag.options.event.stopResize(this.target,
                        (e.newWidth ? (e.newWidth < drag.cont.widgetMinWidth ? drag.cont.widgetMinWidth : e.newWidth) : -1),
                        (e.newHeight ? (e.newHeight < drag.cont.widgetMinHeight ? drag.cont.widgetMinHeight : e.newHeight) : -1)
                    )
                });
            }
        }


        //初始化控件单击事件
        $('.weight').unbind('click').bind('click', function (event) {
            var that = $(this);
            if (drag.cont.isCtrl) {//多选
                log('被点击--CTRL')
                log(that.hasClass('weightSelect'));
                that.hasClass('weightSelect')
                    ?
                    that.removeClass('weightSelect')
                    :
                    that.addClass('weightSelect');
            } else {//单选
                that.siblings().removeClass('weightSelect');
                that.addClass('weightSelect');
            }
            drag.options.event.widgetClick($('.weightSelect'), that, drag.cont.isCtrl)
            return false;//返回False阻止事件冒泡
        })
    },
    initWidgetClick: function (callBack) {

    },
    /**
     *袁泉 2018年2月10日14:02:20
     * @title 初始化左侧控件树
     * @param event 回调事件
     */
    initWidgetList: function (event, xCanvasId) {

        /**************初始化控件************************/

        $('.layui-nav-tree').find('.widget').each(function () {
            var dDrag = $(this).ligerDrag({
                proxy: true, revert: true
                , receive: xCanvasId
            });
            dDrag.unbind('StartDrag');
            dDrag.unbind('DragEnter');
            dDrag.unbind('DragOver');
            dDrag.unbind('DragLeave');
            dDrag.unbind('Drop');
            dDrag.bind('StartDrag', function (a, v, c) {
                var widgetType = a.target.data('type')
                drag.cont.widget = drag.getWidgetObj(widgetType);
                this.cursor = 'not-allowed';
            });
            //当进入区域时
            dDrag.bind('DragEnter', function (receive, source, e) {
                dDrag.cursor = "pointer";
            });
            //在区域移动
            dDrag.bind('DragOver', function (receive, source, e) {
                var x = $(source).offset().left - drag.cont.mWarpLeft;
                var y = $(source).offset().top - drag.cont.mWarpTop;
                drag.cont.widget.x = x;
                drag.cont.widget.y = y;
            });
            //离开区域
            dDrag.bind('DragLeave', function (receive, source, e) {
                this.cursor = "not-allowed";
            });
            //在区域释放
            dDrag.bind('Drop', function (receive, source, e) {
                if (!this.proxy) return;
                this.proxy.hide();
                var itemWidget = $.extend(true, {}, drag.cont.widget);
                event(itemWidget);
            });
        })

    },

    /***
     *到TYPE中获取对应的Widget，生成Widget对象
     * @param widgetType
     * @returns {{}}
     */
    getWidgetObj: function (widgetType) {
        // widgetType 的格式为： type_chlidType
        var types = widgetType.split('_');
        var obj = {};
        TYPE[types[0]].attr && $.each(TYPE[types[0]].attr, function (index, val) {
            // log(val.name)
            // log(val.val)
            if (val.name == 'childType') {
                obj[val.name] = types[1]
                //把子容器的扩展属性也加进来
                $.each(TYPE['panel_' + types[1]].attr, function (i, v) {
                    obj[v.name] = v.val;
                });
            } else if (val.name == 'type') {
                obj[val.name] = types[0];
            } else {
                obj[val.name] = val.val;
            }
        });
        TYPE[types[0]].event && $.each(TYPE[types[0]].event, function (index, val) {
            obj[val.name] = val.val;
            if (val.name == 'childType') {
                obj[val.name] = types[1]
                //把子容器的扩展属性也加进来
                $.each(TYPE['panel_' + types[1]].attr, function (i, v) {
                    obj[v.name] = v.val;
                });
            }
        });
        if (obj['id']) {
            obj.id = 'widget' + drag.util.uuid(5, 16);
        }
        if (obj['name']) {
            obj.name = 'widget' + $('.widgetItem').length;
        }
        return obj;
    },
    initSelectBox: function (selector, selectCallback) {
        function clearBubble(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            } else {
                e.cancelBubble = true;
            }

            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        }

        var $container = selector//$(selector);
        //  框选事件
        $container
            .off('mousedown').on('mousedown', function (eventDown) {
            //  设置选择的标识
            var isSelect = true;
            //  创建选框节点
            var $selectBoxDashed = $('<div class="select-box-dashed"></div>');
            $('body').append($selectBoxDashed);
            //  设置选框的初始位置
            var startX = eventDown.x || eventDown.clientX;
            var startY = eventDown.y || eventDown.clientY;
            $selectBoxDashed.css({
                left: startX,
                top: startY
            });
            //  根据鼠标移动，设置选框宽高
            var _x = null;
            var _y = null;
            //  清除事件冒泡、捕获
            clearBubble(eventDown);
            //  监听鼠标移动事件
            $(selector).off('mousemove').on('mousemove', function (eventMove) {
                //  设置选框可见
                $selectBoxDashed.css('display', 'block');
                //  根据鼠标移动，设置选框的位置、宽高
                _x = eventMove.x || eventMove.clientX;
                _y = eventMove.y || eventMove.clientY;
                //  暂存选框的位置及宽高，用于将 select-item 选中
                var _left = Math.min(_x, startX);
                var _top = Math.min(_y, startY);
                var _width = Math.abs(_x - startX);
                var _height = Math.abs(_y - startY);
                $selectBoxDashed.css({
                    left: _left,
                    top: _top,
                    width: _width,
                    height: _height
                });
                //  遍历容器中的选项，进行选中操作
                $(selector).find('.weight').each(function () {
                    var $item = $(this);
                    var itemX_pos = $item.prop('offsetWidth') + $item.prop('offsetLeft');
                    var itemY_pos = $item.prop('offsetHeight') + $item.prop('offsetTop');
                    //  判断 select-item 是否与选框有交集，添加选中的效果（ temp-selected ，在事件 mouseup 之后将 temp-selected 替换为 selected）
                    var condition1 = itemX_pos > _left;
                    var condition2 = itemY_pos > _top;
                    var condition3 = $item.prop('offsetLeft') < (_left + _width);
                    var condition4 = $item.prop('offsetTop') < (_top + _height);
                    if (condition1 && condition2 && condition3 && condition4) {
                        $item.addClass('weightSelect');
                    } else {
                        $item.removeClass('weightSelect');
                    }
                });
                //  清除事件冒泡、捕获
                clearBubble(eventMove);
            });

            $(document).off('mouseup').on('mouseup', function () {
                $(selector).off('mousemove');
                $(selector)
                    .find('.select-item.temp-selected')
                    .removeClass('temp-selected')
                    .addClass('selected');
                $selectBoxDashed.remove();

                if (selectCallback) {
                    selectCallback();
                }
            });
        });
    }
}
